const app = getApp()
const {
  processListImages
} = require('../../../utils/image')
const request = require('../../../utils/request.js');
Page({
  data: {
    demandId: '',
    demandInfo: {},
    recommendList: [],
    userInfo: null
  },

  onLoad(options) {
    this.setData({
      demandId: options.id
    });
    this.loadDemandDetail();
    this.setData({
      userInfo: app.getGlobalUserInfo()
    })
  },

  // 加载需求详情
  loadDemandDetail() {
    wx.showLoading({
      title: '加载中...'
    });

    request.request({
      url: `${app.globalData.baseUrl}/api/demands/${this.data.demandId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        const data = res.data.data
        data.image = app.globalData.baseUrl + data.image
        this.setData({
          demandInfo: data
        })
        if (data.user.id == this.data.userInfo.id) {
          this.loadRecommendList();
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
        console.error('加载商品详情失败:', err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 加载推荐供应列表
  loadRecommendList() {
    // 模拟推荐算法
    request.request({
      url: `${app.globalData.baseUrl}/api/residues/recommend`,
      method: 'GET',
      data: {
        location: this.data.demandInfo.location,
        type: this.data.demandInfo.type,
        price: this.data.demandInfo.price
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        const mockRecommendList = res.data.data
        // 使用工具函数处理图片URL
        const processedList = processListImages(mockRecommendList)
        this.setData({
          recommendList: processedList
        })
      },
      fail: (err) => {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
        console.error('加载商品列表失败:', err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 跳转到供应详情
  goToSupplyDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/supply/detail/detail?id=${id}`
    });
  },

  // 联系买家
  contactBuyer() {
    if (!this.data.demandInfo.contactPhone) {
      wx.showToast({
        title: '暂无联系方式',
        icon: 'none'
      })
      return
    }

    wx.makePhoneCall({
      phoneNumber: this.data.demandInfo.contactPhone,
      fail: () => {
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        })
      }
    })
  }
});